package com.qf.dao.daoimpl;

import com.qf.dao.ProductDao;
import com.qf.pojo.Product;
import com.qf.utils.dbutilUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author Mr.Liu
 * @date 2021/11/25 13:00
 */

public class ProductDaoImpl implements ProductDao {
    /**
     * 查找最新商品
     * @return返回商品集合
     */
    @Override
    public List<Product> findNewProduct() throws SQLException {
        QueryRunner qr = new QueryRunner(dbutilUtils.getDataSource());
        String sql = "select * from product order by pdate desc limit 9;";
        List<Product> newProduct = qr.query(sql, new BeanListHandler<Product>(Product.class));
        return newProduct;
    }
    /**
     * 查找热门商品
     * @return返回商品集合
     */
    @Override
    public List<Product> findHotProduct() throws SQLException {
        QueryRunner qr = new QueryRunner(dbutilUtils.getDataSource());
        String sql = "select * from product where is_hot = 1 order by pdate desc limit 9;";
        List<Product> hotProduct = qr.query(sql, new BeanListHandler<Product>(Product.class));
        return hotProduct;
    }
    /**
     *通过pid查找商品
     */
    @Override
    public Product findProductByPid(String pid) throws SQLException {
        QueryRunner qr = new QueryRunner(dbutilUtils.getDataSource());
        String sql = "select * from product where pid = ?;";
        Product product = qr.query(sql, new BeanHandler<Product>(Product.class),pid);
        return product;
    }

    /**
     * 通过cid查询总记录数
     * @param cid
     * @return
     * @throws SQLException
     */
    @Override
    public int findTotalSize(String cid) throws SQLException {
        QueryRunner qr = new QueryRunner(dbutilUtils.getDataSource());
        String sql = "select count(pid) from product where cid = ?;";
        Object Total = qr.query(sql, new ScalarHandler<>(), cid);
        String totalSize = String.valueOf(Total);
        int totalsize = Integer.parseInt(totalSize);
        return totalsize;
    }

    @Override
    public List<Product> findProducts(int currentPage, int pageSize,String cid) throws SQLException {
        QueryRunner qr = new QueryRunner(dbutilUtils.getDataSource());
        String sql = "select * from product where cid = ? limit ?,?;";
        List<Product> products = qr.query(sql, new BeanListHandler<Product>(Product.class), cid,(currentPage-1)*pageSize,pageSize);
        return products;
    }
}
